<template>
  <div class="photos-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>相册管理</h2>
        <p>管理博客相册，包括上传、编辑、删除等操作</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showUploadDialog">
          <el-icon><Upload /></el-icon>
          上传照片
        </el-button>
      </div>
    </div>

    <!-- 相册列表 -->
    <div class="photos-list">
      <el-card>
        <div class="photos-grid">
          <div
            v-for="photo in photos"
            :key="photo.id"
            class="photo-item"
            @click="selectPhoto(photo)"
          >
            <div class="photo-image">
              <el-image
                :src="getPhotoUrl(photo.url)"
                fit="cover"
                :preview-src-list="[photo.url]"
              />
              <div class="photo-overlay">
                <div class="photo-actions">
                  <el-button
                    type="primary"
                    size="small"
                    @click.stop="editPhoto(photo)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    @click.stop="deletePhoto(photo.id)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </div>
            <div class="photo-info">
              <h4>{{ photo.title || '未命名' }}</h4>
              <p>{{ photo.description || '暂无描述' }}</p>
              <span class="photo-date">{{ formatDate(photo.created_at) }}</span>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.current_page"
            v-model:page-size="pagination.per_page"
            :page-sizes="[12, 24, 48, 96]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 上传照片对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传照片"
      width="600px"
    >
      <div class="upload-dialog">
        <el-upload
          ref="uploadRef"
          class="upload-area"
          drag
          :auto-upload="false"
          :on-change="handleFileChange"
          :file-list="fileList"
          :limit="1"
          accept="image/*"
          :show-file-list="true"
        >
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传 jpg/png 文件，且不超过 5MB
            </div>
          </template>
        </el-upload>
        <el-form label-width="60px" style="margin-top: 16px;">
          <el-form-item label="标题">
            <el-input v-model="uploadForm.title" placeholder="请输入标题" maxlength="100" show-word-limit />
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="uploadForm.description" type="textarea" :rows="3" placeholder="请输入描述" maxlength="200" show-word-limit />
          </el-form-item>
        </el-form>
        <div v-if="fileList.length" class="upload-list">
          <h4>待上传文件：</h4>
          <div class="upload-item">
            <div class="file-info">
              <span>{{ fileList[0].name }}</span>
              <span class="file-size">{{ formatFileSize(fileList[0].size) }}</span>
            </div>
            <el-button type="danger" size="small" @click="removeFile(0)">移除</el-button>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="uploadPhoto" :loading="uploading" :disabled="!fileList.length || !fileList[0].raw || !uploadForm.title.trim() || !uploadForm.description.trim()">开始上传</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑照片对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑照片"
      width="500px"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item label="照片">
          <el-image
            :src="editForm.url"
            style="width: 200px; height: 150px; object-fit: cover;"
          />
        </el-form-item>
        
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="editForm.title"
            placeholder="请输入照片标题"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入照片描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePhoto" :loading="saving">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload, UploadFilled } from '@element-plus/icons-vue'
import { photoApi } from '@/api/admin'

// 照片列表
const photos = ref([])
const loading = ref(false)

// 分页
const pagination = ref({
  current_page: 1,
  per_page: 24,
  total: 0
})

// 上传对话框
const uploadDialogVisible = ref(false)
const uploadRef = ref(null)
const fileList = ref([])
const uploading = ref(false)
const uploadForm = ref({
  title: '',
  description: ''
})

// 编辑对话框
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = ref({
  id: null,
  title: '',
  description: '',
  url: ''
})
const saving = ref(false)

// 编辑表单验证规则
const editRules = {
  title: [
    { max: 100, message: '标题不能超过 100 个字符', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 获取照片列表
const fetchPhotos = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.value.current_page,
      per_page: pagination.value.per_page
    }
    const response = await photoApi.getPhotos(params)
    console.log(response)
    photos.value = response.data || []
    pagination.value = {
      current_page: response.meta?.current_page || 1,
      per_page: response.meta?.per_page || 24,
      total: response.meta?.total || 0
    }
  } catch (error) {
    console.error('获取照片列表失败:', error)
    ElMessage.error('获取照片列表失败')
  } finally {
    loading.value = false
  }
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.value.per_page = size
  pagination.value.current_page = 1
  fetchPhotos()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.value.current_page = page
  fetchPhotos()
}

// 显示上传对话框
const showUploadDialog = () => {
  fileList.value = []
  uploadForm.value = { title: '', description: '' }
  uploadDialogVisible.value = true
}

// 文件变化处理
const handleFileChange = (file, fileListNew) => {
  // 只保留最新的一个文件
  fileList.value = fileListNew.slice(-1)
  const current = fileList.value[0]
  if (!current) return
  const isImage = current.raw && current.raw.type.startsWith('image/')
  const isLt5M = current.raw && current.raw.size / 1024 / 1024 < 5
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    fileList.value = []
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    fileList.value = []
    return false
  }
}

// 移除文件
const removeFile = (index) => {
  fileList.value.splice(index, 1)
}

// 上传照片
const uploadPhoto = async () => {
  if (!fileList.value.length) {
    ElMessage.warning('请选择要上传的文件')
    return
  }
  if (!uploadForm.value.title.trim()) {
    ElMessage.warning('请输入标题')
    return
  }
  try {
    uploading.value = true
    const formData = new FormData()
    formData.append('file', fileList.value[0].raw)
    formData.append('title', uploadForm.value.title)
    formData.append('description', uploadForm.value.description)
    await photoApi.uploadPhoto(formData)
    

    ElMessage.success('照片上传成功')
    uploadDialogVisible.value = false
    fetchPhotos()
  } catch (error) {
    console.error('上传照片失败:', error)
    ElMessage.error('上传照片失败')
  } finally {
    uploading.value = false
  }
}

// 选择照片
const selectPhoto = (photo) => {
  // 可以在这里添加照片预览或其他操作
}

// 编辑照片
const editPhoto = (photo) => {
  editForm.value = {
    id: photo.id,
    title: photo.title || '',
    description: photo.description || '',
    url: photo.url
  }
  editDialogVisible.value = true
}

// 保存照片
const savePhoto = async () => {
  try {
    await editFormRef.value.validate()
    saving.value = true
    await photoApi.updatePhoto({
      id: editForm.value.id,
      title: editForm.value.title,
      description: editForm.value.description
    })
    ElMessage.success('照片更新成功')
    editDialogVisible.value = false
    fetchPhotos()
  } catch (error) {
    if (error !== false) {
      console.error('保存照片失败:', error)
      ElMessage.error('保存照片失败')
    }
  } finally {
    saving.value = false
  }
}

// 删除照片
const deletePhoto = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这张照片吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await photoApi.deletePhoto({ id })
    ElMessage.success('删除成功')
    fetchPhotos()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除照片失败:', error)
      ElMessage.error('删除照片失败')
    }
  }
}

// 获取照片URL
const getPhotoUrl = (url) => {
  if (!url) return ''
  if (/^https?:\/\//.test(url)) return url
  const base = import.meta.env.VITE_API_BASE_URL?.replace(/\/$/, '') || ''
  if (url.startsWith('/')) {
    return `${base}${url}`
  }
  if (url.startsWith('storage/')) {
    return `${base}/${url}`
  }
  if (url.startsWith('photos/')) {
    return `${base}/storage/${url}`
  }
  return `${base}/${url}`
}

// 组件挂载
onMounted(() => {
  fetchPhotos()
})
</script>

<style scoped lang="scss">
.photos-page {
  background: #fafbfc;
  min-height: 100vh;
  padding: 32px 0;

  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24px;
  }

  .page-title {
    font-size: 24px;
    font-weight: 700;
    color: #222;
  }

  .photos-list {
    .photos-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
      gap: 20px;
      margin-bottom: 24px;

      .photo-item {
        border: 1px solid #e4e7ed;
        border-radius: 8px;
        overflow: hidden;
        cursor: pointer;
        transition: transform 0.2s, box-shadow 0.2s;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .photo-image {
          position: relative;
          height: 200px;

          .el-image {
            width: 100%;
            height: 100%;
          }

          .photo-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.6);
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 1;
            transition: none;

            .photo-actions {
              display: flex;
              gap: 8px;
            }
          }
        }

        .photo-info {
          padding: 12px;

          h4 {
            margin: 0 0 8px 0;
            font-size: 16px;
            color: #303133;
          }

          p {
            margin: 0 0 8px 0;
            font-size: 14px;
            color: #606266;
            line-height: 1.4;
          }

          .photo-date {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }

    .pagination-wrapper {
      display: flex;
      justify-content: center;
    }
  }
}

.photos-table {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  padding: 24px;
}

.upload-dialog {
  .upload-area {
    margin-bottom: 20px;
  }

  .upload-list {
    h4 {
      margin: 0 0 12px 0;
      color: #303133;
    }

    .upload-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 12px;
      background: #f5f7fa;
      border-radius: 4px;
      margin-bottom: 8px;

      .file-info {
        display: flex;
        flex-direction: column;
        gap: 4px;

        .file-size {
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .photos-page {
    padding: 16px 0;
  }
  .photos-table {
    border-radius: 12px;
    padding: 12px;
  }
  .page-title {
    font-size: 18px;
  }
  .photos-list {
    .photos-grid {
      grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      gap: 16px;
    }
  }
}
</style> 